<?php

namespace Battlelog;

class User
{
    private $id;
    private $username;
    private $db;
    private $user_id;
	private $user_dsnm;
	private $user_dta;
	private $user_dtb;
	private $user_clantag;
	private $user_rank;
	private $user_location;
	private $user_ingame;
	private $user_gravatar;
    private $is_authorized = false;

    public function __construct($username = null, $password = null)
    {
		require_once( "./includes/config.php" );
		$this->username = $username;
		$this->connectDb(DB_DSN, DB_USERNAME, DB_PASSWORD);
    }

    public function __destruct()
    {
        $this->db = null;
    }
	public static function UserPID()
	{
		return $_SESSION["user_id"];		
	}
	public static function UserGRAVATAR()
	{
		return $_SESSION["user_gravatar"];		
	}
	public static function UserLOC()
	{
		return $_SESSION["user_location"];		
	}
	public static function UserINGAME()
	{
		return $_SESSION["user_ingame"];		
	}
	public static function UserDSNM()
	{
		return $_SESSION["user_dsnm"];		
	}
	
	public static function UserDTA()
	{
		return $_SESSION["user_dta"];		
	}
	
	public static function UserDTB()
	{
		return $_SESSION["user_dtb"];		
	}
	
	public static function UserCLNTG()
	{
		return $_SESSION["user_clantag"];		
	}
	
	public static function UserRANK()
	{
		return $_SESSION["user_rank"];		
	}
	public static function UpdateUserGRAVATAR($gravatar)
	{
		$_SESSION["user_gravatar"] = $gravatar;
	}
	public static function UpdateUserINGAME($ingame)
	{
		$_SESSION["user_ingame"] = $ingame;
	}
	public static function UpdateUserDTA($dta)
	{
		$_SESSION["user_dta"] = $dta;
	}
	public static function UpdateUserDTB($dtb)
	{
		$_SESSION["user_dtb"] = $dtb;
	}
	public static function UpdateUserCLNTG($clantag)
	{
		$_SESSION["user_clantag"] = $clantag;
	}
	public static function UpdateUserRANK($rank)
	{
		$_SESSION["user_rank"] = $rank;
	}
	
    public static function isAuthorized()
    {
        if (!empty($_SESSION["user_id"]))
		{
            return (bool) $_SESSION["user_id"];
        }
        return false;
    }

	public function UpdateUserTimeLogin($pid, $time)
	{
		$query = "update players set time=NOW() where pid=".$pid."";
		$sth = $this->db->prepare($query);
		$sth->execute();
	}
	
	public function LoadRank($pid)
	{
		$query = 'SELECT value FROM playerstats WHERE `pid` = "'.$pid.'" AND `statname` = "rank"';
		
		$sth = $this->db->prepare($query);
		$sth->execute();
		
		while ($row = $sth->fetch())
		{
			$rank = round($row['value']);
		}
		$this->user_rank = $rank;
	}
	
    public function authorize($username, $password, $remember=false)
    {
        $query = "select pid, dsnm, gravatar, inGame, localPlayer, dta, dtb, clantag from players where dsnm = :username and password = :password limit 1";
		$sth = $this->db->prepare($query);
        $password = md5(trim(htmlspecialchars($password))); 
		$sth->execute(array(":username" => $username, ":password" => $password,));
		$this->user = $sth->fetch();
        
        if (!$this->user)
		{
            $this->is_authorized = false;
        }
		else
		{
			$this->is_authorized = true;
            $this->user_id = $this->user['pid'];
			$this->user_dsnm = $this->user['dsnm'];
			$this->user_gravatar = !empty($this->user['gravatar']) ? "".$this->user['gravatar']:  "default-avatar-60.png";
			$this->user_location = $this->user['localPlayer'];
			$this->user_ingame = $this->user['inGame'];
			$this->user_dta = $this->user['dta'];
			$this->user_dtb = $this->user['dtb'];
			$this->user_clantag = $this->user['clantag'];
			$this->LoadRank($this->user['pid']);		
			$this->saveSession($remember);
			$this->UpdateUserTimeLogin($this->user['pid']);		
			
        }
		return $this->is_authorized;
    }

    public function saveSession($remember = false, $http_only = true, $days = 7)
    {
        $_SESSION["user_id"] = $this->user_id;
		$_SESSION["user_dsnm"] = $this->user_dsnm;
		$_SESSION["user_dta"] = $this->user_dta;
		$_SESSION["user_dtb"] = $this->user_dtb;
		$_SESSION["user_clantag"] = $this->user_clantag;
		$_SESSION["user_rank"] = $this->user_rank;
		$_SESSION["user_location"] = $this->user_location;
		$_SESSION["user_ingame"] = $this->user_ingame;
		$_SESSION["user_gravatar"] = !empty($this->user['gravatar']) ? "".$this->user['gravatar']:  "default-avatar-36.png";

        if ($remember)
		{
            // Save session id in cookies
            $sid = session_id();

            $expire = time() + $days * 24 * 3600;
            $domain = ""; // default domain
            $secure = false;
            $path = "/";

            $cookie = setcookie("sid", $sid, $expire, $path, $domain, $secure, $http_only);
        }
    }
	
	public function create($username, $password) 
	{
        $user_exists = $this->getname($username);
		$localPlayer = 0;
        if ($user_exists) 
		{
            throw new \Exception("User exists: " . $username, 1);
        }

        $query = "insert into players (dsnm, password, localPlayer)
            values (:username, :password, :localPlayer)";
        
		
		$password = $this->passwordHash($password);
        $sth = $this->db->prepare($query);

        try {
            $this->db->beginTransaction();
            $result = $sth->execute(
                array(
                    ':username' => $username,
                    ':password' => $password,
					':localPlayer' => $localPlayer,
                 )
            );
            $this->db->commit();
        } catch (\PDOException $e) {
            $this->db->rollback();
            echo "Database error: " . $e->getMessage();
            die();
        }

        if (!$result) {
            $info = $sth->errorInfo();
            printf("Database error %d %s", $info[1], $info[2]);
            die();
        } 

        return $result;
    }

    public function connectdb($db_dsn, $db_user, $db_pass)
    {
        try
		{
			$this->db = new \pdo($db_dsn, $db_user, $db_pass );
	
        }
		catch (\pdoexception $e)
		{
            echo "database error: " . $e->getmessage();
			file_put_contents('MysqlErrors.txt', $e->getMessage(), FILE_APPEND);  
            die();
        }
        $this->db->query('set names utf8');
		return $this;
    }
		
	public function passwordHash($password)
    {
		$password = md5(trim(htmlspecialchars($password))); 
		return $password;
    }

    public function getname($username) 
	{
        $query = "select dsnm from players where dsnm = :username limit 1";
        $sth = $this->db->prepare($query);
        $sth->execute(
            array(
                ":username" => $username
            )
        );
        $row = $sth->fetch();
        if (!$row) 
		{
            return false;
        }
		else
		{
			return true;
		}
        //return $row["salt"];
    }
}
